package Filter;

import com.alibaba.fastjson.JSONObject;
import vo.ResultBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginFilter extends HttpFilter {
	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest) req;
		if(request.getRequestURI().contains("/login")) {
			chain.doFilter(req,res);
			return ;
		}
		HttpSession session=request.getSession();
		System.out.println("登录验证："+session.getId());
		//从session中获取adminUser
		Object adminUser=session.getAttribute("adminUser");
		System.out.println("adminUser---"+adminUser);
		//如果adminUser存在，就证明登陆过，且没有超时 放行
		if(adminUser!=null) {
			chain.doFilter(req,res);
		} else {
			res.getWriter().write(JSONObject.toJSONString(ResultBean.ERROR(50001,
					"未登录，请重新登录")));
		}
	}
}
